/**
 * Created by liuqingxia on 2016/2/1.
 */

var url = getUrlBySuffix("/job/insert");// 后台提交任务地址

var readerFormId = "reader-form-drds";// reader表单id，默认drds
var writerFormId = "writer-form-drds";// writer表单id，默认drds

var readerType = "drds";// 默认reader类型
var writerType = "drds";// 默认writer类型

// reader数据源属性
var readerDataSourceProps = [ "readerUsername", "readerPassword",
		"readerJdbcUrl", "readerJdbcUrls" ];

// writer数据源属性
var writerDataSourceProps = [ "writerUsername", "writerPassword",
		"writerJdbcUrl" ];

// 可与querySql属性二选一的属性项
var readerPropsAgainstQuerySql = [ "readerTable", "readerColumns",
		"readerWhere" ];

var params = {};// 发送给后台的表单参数

// reader中可选填的属性
var skipReaderProps = {
	drds : [ "readerWhere", "readerQuerySql" ],
	mongodb : [],
	mysql : [ "readerSplitPk", "readerQuerySql", "readerWhere" ],
	sqlserver : [ "readerSplitPk", "readerQuerySql", "readerWhere" ],
	oracle : [ "readerSplitPk", "readerWhere", "readerQuerySql" ],
	hdfs : [ "readerEncoding", "readerFieldDelimiter" ],
	hbase : [ "readerEncoding", "readerStartRowkey", "readerEndRowkey",
			"readerIsBinaryRowkey" ]
};

// writer中可选填的属性
var skipWriterProps = {
	drds : [ "writerPreSql" ],
	mongodb : [],
	mysql : [ "writerPreSql", "writerSession" ],
	oracle : [ "writerPreSql" ],
	hdfs : [],
	gcache : [ "writerExtendFields", "writerOextendField" ]
};

var writerNotSearchTableName = [ 'gcache' ];

function hideSearchTableDiv(direction) {
	$("#" + direction + "SearchTableDiv").hide();
}

/**
 * 判断reader或writer的属性是选填还是必填
 * 
 * @param prop
 * @returns {boolean}
 */
function canSkip(prop) {
	var readerArray = skipReaderProps[readerType];
	var writerArray = skipWriterProps[writerType];
	if (readerArray.indexOf(prop) == -1 && writerArray.indexOf(prop) == -1) {
		return canSkipReaderPropWhichAgainstQuerySql(prop);
	}
	return true;
}

/**
 * 是否是一个可以和querySql二选一的reader属性项
 * 
 * @param readerProp
 * @returns {boolean}
 */
function isReaderPropWhichAgainstQuerySql(readerProp) {
	return readerPropsAgainstQuerySql.indexOf(readerProp) != -1;
}

/**
 * 与querySql二选一的reader属性项是否可以不填（readerQuerySql已赋值）
 * 
 * @param readerProp
 * @returns {boolean}
 */
function canSkipReaderPropWhichAgainstQuerySql(readerProp) {
	if (isReaderPropWhichAgainstQuerySql(readerProp)) {
		if (!isNull(params['readerQuerySql'])) {
			return true;
		}
	}
	return false;
}

/**
 * 注册readerType选择框改变事件
 */
function registerChangeReaderTypeSelectEvent() {
	$(document).on("change", "select[name='readerType']", function() {
		readerType = $(this).val();
		changeGuideLinkHref("/guide/reader/", readerType, "reader");
		showReaderFormByType(readerType);
		showReaderDataSourceSelect(readerType);
		showReaderTableSelect(readerType);
		hideTableColumnsCheckBoxDiv("reader");
	});
}

/**
 * 注册writerType选择框改变事件
 */
function registerChangeWriterTypeSelectEvent() {
	$(document).on("change", "select[name='writerType']", function() {
		writerType = $(this).val();
		if (writerNotSearchTableName.indexOf(writerType) != -1) {
			hideSearchTableDiv("writer");
		}
		changeGuideLinkHref("/guide/writer/", writerType, "writer");
		showWriterFormByType(writerType);
		showWriterDataSourceSelect(writerType);
		showWriterTableSelect(writerType);
		hideTableColumnsCheckBoxDiv("writer");
	});
}

/**
 * 改变使用指南连接的href属性
 * 
 * @param Type
 */
function changeGuideLinkHref(url, type, prefix) {
	var href = getUrlBySuffix(url + type);
	$("#" + prefix + "-guide-link").attr("href", href);
}

/**
 * 根据readerType选择相应的reader表单
 * 
 * @param readerType
 */
function showReaderFormByType(readerType) {
	readerFormId = "reader-form-" + readerType;
	$("[id^=reader-form]").hide();
	$("#" + readerFormId).show();
}

/**
 * 根据writerType选择相应的writer表单
 * 
 * @param writerType
 */
function showWriterFormByType(writerType) {
	writerFormId = "writer-form-" + writerType;
	$("[id^=writer-form]").hide();
	$("#" + writerFormId).show();
}

/**
 * 注册writerHdfsFileType选择框改变事件
 */
function registerChangeWriterHdfsFileTypeSelectEvent() {
	$(document).on("change", "#writer-fileType-select", function() {
		$("[id^=compress-]").hide();
		var writerFileType = $(this).val();
		var compressDivId = "#compress-" + $.trim(writerFileType);
		$(compressDivId).show();
	});
}

/**
 * 提取Enum类型Reader的int值
 * 
 * @param str
 * @returns {*}
 */
function getReaderInt(str) {
	var readerInt;
	switch (str) {
	case "drds":
		readerInt = 0;
		break;
	case "mongodb":
		readerInt = 1;
		break;
	case "mysql":
		readerInt = 2;
		break;
	case "oracle":
		readerInt = 3;
		break;
	case "hdfs":
		readerInt = 4;
		break;
	case "hbase":
		readerInt = 5;
		break;
	case "sqlserver":
		readerInt = 7;
		break;
	default:
		swal("警告", "reader类型错误，没有此类型:" + str, "warning");
	}
	return readerInt;
}

/**
 * 提取Enum类型Writer的int值
 * 
 * @param str
 * @returns {*}
 */
function getWriterInt(str) {
	var writerInt;
	switch (str) {
	case "drds":
		writerInt = 0;
		break;
	case "mongodb":
		writerInt = 1;
		break;
	case "mysql":
		writerInt = 2;
		break;
	case "oracle":
		writerInt = 3;
		break;
	case "stream":
		writerInt = 4;
		break;
	case "hdfs":
		writerInt = 5;
		break;
	case "gcache":
		writerInt = 6;
		break;
	case "sqlserver":
		writerInt = 7;
		break;
	default:
		swal("警告", "writer类型错误，没有此类型:" + str, "warning");
	}
	return writerInt;
}

/**
 * 注册点击“生成cron表达式按钮”
 */
function registerClickShowCronGenBtnEvent() {
	$(document).on("click", "#showCronGen-btn", function() {
		$("#cronGenerator-modal").modal("show");
	});
}

/**
 * 注册点击cron表达式生成模态框中的标签页title标签事件
 */
function registerClickCronGenTabTitleBtnEvent() {
	$(document).on("click", "button[id^='tab-title-']", function() {
		$("button[id^='tab-title-']").removeClass("clickedTab");
		$(this).addClass("clickedTab");
		var title = $(this).attr("title");
		var tabTitleShow = "#tab-title-show-" + $.trim(title);
		$("[id^=tab-title-show-]").hide();
		$(tabTitleShow).show();
	});
}

/**
 * 注册点击cron表达式生成模态框中的生成按钮
 */
function registerClickCronGenCommitBtnEvent() {
	$(document).on("click", "button[id='commit-cronGen-btn']", function() {
		var cronVal = $("#cron").val();
		cronVal = $.trim(cronVal);
		$("#cronExpression").val(cronVal);
		$("#shutdown-modal").click();

	});
}

/**
 * 注册点击任务添加按钮事件
 */
function registerClickSaveJobBtnEvent() {
	$(document).on(
			"click",
			"#addBtn",
			function() {

				params['readerType'] = getReaderInt(readerType);
				params['writerType'] = getWriterInt(writerType);
				$.extend(params, getFormValuesSkip(readerFormId));
				$.extend(params, getFormValuesSkip(writerFormId));

				if (isNull(params['readerQuerySql'])) {
					if (haveDataSource(readerType)) {
						if (!getDataSourceParams("reader")) {
							return;
						}
					}
				}

				if (isNull(params['writerQuerySql'])) {
					if (haveDataSource(writerType)) {
						if (!getDataSourceParams("writer")) {
							return;
						}
					}
				}

				if (!validateParams(params)) {
					return;
				}

				var speedLimitType = $("#speedLimitType").val();
				if (isNull(speedLimitType)) {
					swal("警告", "请选择速度限制类型", "warning");
					return;
				}
				if (speedLimitType == "bytes") {
					speedLimitType = 0;
				}
				if (speedLimitType == "record") {
					speedLimitType = 1;
				}

				var introduce = $("#introduce").val();
				if (isNull(introduce)) {
					swal("警告", "请输入任务备注", "warning");
					return;
				}

				var speedLimitValue = $("#speedLimitValue").val();
				if (isNull(speedLimitValue)) {
					swal("警告", "请输入限制值", "warning");
					return;
				}

				var projectName = $("#projectName").val();
				if (isNull(projectName)) {
					swal("警告", "请选择组名", "warning");
					return;
				}

				params['introduce'] = introduce;
				params['speedLimitType'] = speedLimitType;
				params['speedLimitValue'] = speedLimitValue;
				params['pipelineName'] = projectName;
				params["projectId"] = getProjectIdByProjectName(projectName);

				if (!getExecuteTypeParams(params)) {
					return;
				}

				if (params['writerDataStructure'] == "APPEND"
						|| params['writerDataStructure'] == "SADD"
						|| params['writerDataStructure'] == "ZADD") {
					params['writerOextendField'] = "";
					params['writerVdataStructure'] = "";
				}
				$.postHttp(params, url, showJsonMsg);

				params = {};
			});
}

/**
 * 获取数据源相关参数
 * 
 * @param readerOrWriter
 * @returns {boolean}
 */
function getDataSourceParams(readerOrWriter) {
	if (getTableNameParam(readerOrWriter)) {
		return getTableColumnParam(readerOrWriter);
	}
	return false;
}

/**
 * 获取表名
 * 
 * @param readerOrWriter
 * @returns {boolean}
 */
function getTableNameParam(readerOrWriter) {
	var tableName = $("#" + readerOrWriter + "-table-select").val();
	tableName = $.trim(tableName);
	if (isNull(tableName)) {
		swal("警告", "请选择" + readerOrWriter + "表", "warning");
		return false;
	}
	params[readerOrWriter + "Table"] = $.trim(tableName);
	return true;
}

/**
 * 获取列
 * 
 * @param readerOrWriter
 * @returns {boolean}
 */
function getTableColumnParam(readerOrWriter) {
	var columns = "";
	$.each($("." + readerOrWriter + "-tableColumn-checkBox"), function(index,
			ele) {
		if (ele.checked == true) {
			var value = $(this).val();
			if (index == 0) {
				columns += value;
				return true;
			}
			columns += "," + value;
		}
	});
	if (isNull(columns)) {
		swal("警告", "请选择" + readerOrWriter + "列", "warning");
		return false;
	}
	params[readerOrWriter + 'Columns'] = $.trim(columns);
	return true;
}

/**
 * 验证reader或者writer参数
 * 
 * @param params
 * @returns {boolean}
 */
function validateParams(params) {
	for ( var p in params) {
		if (typeof (params[p]) != "function" && isNull(params[p])) {
			if (!canSkip(p)) {
				readerOrWriterSwal(p);
				return false;
			}
		}
	}
	return true;
}

/**
 * 对reader或者writer参数的空值提示
 * 
 * @param nullProp
 */
function readerOrWriterSwal(nullProp) {
	if (readerDataSourceProps.indexOf(nullProp) != -1) {
		swal("警告", "请选择reader数据源", "warning");
		return;
	}
	if (writerDataSourceProps.indexOf(nullProp) != -1) {
		swal("警告", "请选择writer数据源", "warning");
		return;
	}
	emptySwal(nullProp);
	return;
}

/**
 * 表单中的某个必填项为空时，给予用户提示
 * 
 * @param propName
 */
function emptySwal(propName) {
	var type = propName.substring(0, 6);
	propName = propName.substring(6);
	swal("警告", type + "的参数" + propName + "不能为空", "warning");
}

/**
 * 根据项目组名获取项目组id
 * 
 * @param projectName
 */
function getProjectIdByProjectName(projectName) {
	var findByNameUrl = getUrlBySuffix("/project/findByName");
	var params = {};
	var id;
	params['projectName'] = projectName;
	$.postHttpSync(params, findByNameUrl, function(json) {
		if (json && json.success) {
			var list = json['list'];
			var project = list[0];
			id = project.id;
		}
	});
	return id;
}